/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "memorymap.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "arm_math.h"
#include "string.h"
#include "filter.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
#define MABS(n) (((n)>=0)?(n):(-(n)))
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

#define SMPS 1e6

volatile uint8_t adc_buffer_flag = 0;
#define fft_length 4096
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) uint16_t adc_buffer[ADC_BUFFER_SIZE]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) float32_t fft_input[fft_length]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) float32_t amp_buffer[fft_length]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) float32_t window_buffer[fft_length]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) float32_t fft_output[fft_length+2]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) int16_t freq_map[fft_length/2+2]);
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) float32_t freq_add[fft_length/2+1]);

ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) uint16_t trg[32])=
{2048,2303,2558,2813,3068,3323,3578,3833,4088,3833,3578,3323,3068,2813,2558,2303,2048,1793,1538,1283,1028,773,518,263,8,263,518,773,1028,1283,1538,1793};
	
ALIGN_32BYTES(__attribute__((section(".AXI_RAM"))) uint16_t sine[32])=
{2048,2446,2829,3181,3490,3744,3933,4049,4088,4049,3933,3744,3490,3181,2829,2446,2048,1650,1267,915,606,352,163,47,8,47,163,352,606,915,1267,1650};

float32_t adc_amp = 3.3/1024;
float32_t output_scale = SMPS/fft_length;

#define FREQ_DIVISIONS 80

float gate=1;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MPU_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MPU Configuration--------------------------------------------------------*/
  MPU_Config();

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_TIM2_Init();
  MX_TIM5_Init();
  MX_TIM1_Init();
  MX_TIM8_Init();
  MX_USART1_UART_Init();
  MX_ADC1_Init();
  MX_DAC1_Init();
  /* USER CODE BEGIN 2 */
	
	/**************** UART & Clock Tick Start ****************/
	HAL_TIM_Base_Start(&htim5);
  printf("uart1\n");

	/**************** FFT Constants Init ****************/
  for(int i=0;i<fft_length;i++)
  {
    amp_buffer[i] = adc_amp;
    // hamming window
    // window_buffer[i] = 0.53836 + (1-0.53836)*arm_cos_f32(2*PI*i/(fft_length-1));
		
		// blackman window
		window_buffer[i] = 0.42f + 0.5f*arm_cos_f32(2*3.14159f*i/(fft_length-1)) + 0.08f*arm_cos_f32(4*3.14159f*i/(fft_length-1));
  }

  for(int i=0,j=1;j<FREQ_DIVISIONS && i<fft_length/2+1;j++)
  {
    while(i++*output_scale<j*5e3-1e3);
    while(i*output_scale<=j*5e3+1e3)
    {
      freq_map[i] = j;
      i++;
    }
  }

	/**************** TIM-DMA-ADC Conduct ****************/
  HAL_TIM_Base_Start(&htim2);
  HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buffer, ADC_BUFFER_SIZE);
	
	while(!adc_buffer_flag);
	adc_buffer_flag=0;
	HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc_buffer, ADC_BUFFER_SIZE);
	
	while(!adc_buffer_flag);
	HAL_TIM_Base_Stop(&htim2);
	HAL_ADC_Stop_DMA(&hadc1);
	
	/**************** FFT Conduct ****************/
	// differential handling
	for(int i=0;i<fft_length;i++)
	{
		// differential
		fft_input[i] = (float32_t)adc_buffer[i+1] - (float32_t)adc_buffer[i];
	}

	arm_mult_f32(fft_input,amp_buffer,fft_input,fft_length);
	arm_mult_f32(fft_input,window_buffer,fft_input,fft_length);
	
	// fft
	arm_rfft_fast_instance_f32 S;
	arm_rfft_fast_init_f32(&S,fft_length);
	arm_rfft_fast_f32(&S,fft_input, fft_output, 0);

	arm_cmplx_mag_squared_f32(fft_output,fft_output,fft_length/2+1);

	/**************** Frequency Distinguishment ****************/
	// add up to PSD
	memset(freq_add,0,sizeof(freq_add));
	for(int i=0;i<fft_length/2+1;i++)
	{
		if(freq_map[i]!=0)
		{
			freq_add[freq_map[i]-1] += fft_output[i];
		}
	}

	// fix differential and check PSD
	for(int i=0;i<FREQ_DIVISIONS;i++)
	{
		freq_add[i] /= (i+1)*(i+1);
	}
	
	uint32_t freq1,freq2;
	float32_t vol1,vol2;
	arm_max_f32(freq_add,20,&vol1,&freq1);
	freq_add[freq1]=0;
	arm_max_f32(freq_add,20,&vol2,&freq2);
	freq_add[freq2]=0;
	
	freq1=(freq1+1)*5000;
	freq2=(freq2+1)*5000;
	
	// add up differential PSD
	uint8_t triangle = 0;
	if(freq2<freq1)
	{
		float32_t t = vol1;
		vol1 = vol2;
		vol2 = t;
		
		uint32_t f = freq1;
		freq1 = freq2;
		freq2 = f;
	}
	
	printf("%e:%e\n%e:%e\n",(double)freq1,vol1,(double)freq2,vol2);
	
	// analysis frequency map
	if(freq_add[freq2*3/5000-1] > vol2/243)
	{
		triangle=2;
	}
	else if(MABS((int32_t)freq2-3*(int32_t)freq1)>=10000-1)
	{
		if(freq_add[freq1*3/5000-1] > vol1/243)
		triangle = 1;
	}
	else
	{
		for(int i=0;i<FREQ_DIVISIONS;i++)
		{
			freq_add[i] *= (i+1)*(i+1);
		}
		float32_t b3 = freq_add[freq1*5/5000-2] + freq_add[freq1*5/5000];
		if(freq_add[freq1*5/5000-1]>b3) triangle = 1;
	}
	
	printf("triangle: %d\n", triangle);
	
	/**************** TIM-PWM-IC & DAC Init ****************/
	HAL_TIM_Base_Start(&htim1);
	HAL_TIM_Base_Start(&htim8);
	HAL_DAC_Start_DMA(&hdac1,DAC_CHANNEL_1,(uint32_t*)trg,32,DAC_ALIGN_12B_R);
	HAL_DAC_Start_DMA(&hdac1,DAC_CHANNEL_2,(uint32_t*)sine,32,DAC_ALIGN_12B_R);
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
	}
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Supply configuration update enable
  */
  HAL_PWREx_ConfigSupply(PWR_LDO_SUPPLY);

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE0);

  while(!__HAL_PWR_GET_FLAG(PWR_FLAG_VOSRDY)) {}

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 2;
  RCC_OscInitStruct.PLL.PLLN = 40;
  RCC_OscInitStruct.PLL.PLLP = 1;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 2;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLL1VCIRANGE_3;
  RCC_OscInitStruct.PLL.PLLVCOSEL = RCC_PLL1VCOWIDE;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_D3PCLK1|RCC_CLOCKTYPE_D1PCLK1;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.SYSCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_APB3_DIV2;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_APB1_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_APB2_DIV2;
  RCC_ClkInitStruct.APB4CLKDivider = RCC_APB4_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
  {
    Error_Handler();
  }

  /** Enables the Clock Security System
  */
  HAL_RCC_EnableCSS();
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

 /* MPU Configuration */

void MPU_Config(void)
{
  MPU_Region_InitTypeDef MPU_InitStruct = {0};

  /* Disables the MPU */
  HAL_MPU_Disable();

  /** Initializes and configures the Region and the memory to be protected
  */
  MPU_InitStruct.Enable = MPU_REGION_ENABLE;
  MPU_InitStruct.Number = MPU_REGION_NUMBER0;
  MPU_InitStruct.BaseAddress = 0x0;
  MPU_InitStruct.Size = MPU_REGION_SIZE_4GB;
  MPU_InitStruct.SubRegionDisable = 0x87;
  MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0;
  MPU_InitStruct.AccessPermission = MPU_REGION_NO_ACCESS;
  MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE;
  MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE;
  MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE;
  MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE;

  HAL_MPU_ConfigRegion(&MPU_InitStruct);
  /* Enables the MPU */
  HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT);

}

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
